"""
此代码列出了屏幕的常用绘图函数。
"""

import sensor
import image
import lcd
from Maix import GPIO
from fpioa_manager import fm
from board import board_info
import os, sys
import time

def camera_init():
  sensor.reset()
  sensor.set_pixformat(sensor.RGB565)
  sensor.set_framesize(sensor.QVGA)
  sensor.skip_frames(10)
  sensor.run(1)


lcd.init(freq=15000000, color=65535, invert=1)
lcd.rotation(2)
camera_init()
sensor.set_windowing((320, 240))
sensor.set_vflip(1)
sensor.set_hmirror(1)

#### boot key ####
boot_pin = 16 # board_info.BOOT_KEY
fm.register(boot_pin, fm.fpioa.GPIOHS0)
key = GPIO(GPIO.GPIOHS0, GPIO.PULL_UP)#上拉输入
#### 初始颜色 ####
yanse_threshold   = [44, 68, -26, 25, 26, 68]#lab颜色值
yanse_lab = [50,0,45]
yanse = image.lab_to_rgb(yanse_lab)

while True:
    img = sensor.snapshot()#获取一张照片
    blobs = img.find_blobs([yanse_threshold])#获取颜色
    if blobs:#如果识别得到的话
        max_area = 0
        max_i = 0
        for i, j in enumerate(blobs): #查找最大面积最大的对象 i为索引值
            a = j.w()*j.h()
            if a > max_area:
                max_i = i       #索引
                max_area = a    #最大值的值
        core_y= blobs[max_i].y() + blobs[max_i].h() / 2
        core_x= blobs[max_i].x() + blobs[max_i].w() / 2
        c = img.get_pixel(int(core_x), int(core_y))
        img = img.draw_rectangle(blobs[max_i].rect(),(255,0,255),1,0)#画方框

    img = img.draw_rectangle([154,114,12,12],yanse,1,0)	#绘制中心矩形
    img = img.draw_rectangle([1,40,40,40],yanse,1,1)	#绘制颜色填充矩形

    if key.value() == 0:
        time.sleep_ms(10)
        if key.value() == 0:
            #yanse = img.get_pixel([160,120])

            histogram = img.get_histogram(roi=[155,115,10,10])# 获取颜色值
            yanse_lab[0] = histogram.get_percentile(0.5).l_value()
            yanse_threshold[0] = yanse_lab[0]-10
            yanse_threshold[1] = yanse_lab[0]+10

            yanse_lab[1] = histogram.get_percentile(0.5).a_value()
            yanse_threshold[2] = yanse_lab[1] - 10
            yanse_threshold[3] = yanse_lab[1] + 10

            yanse_lab[2] = histogram.get_percentile(0.5).b_value()
            yanse_threshold[4] = yanse_lab[2]-10
            yanse_threshold[5] = yanse_lab[2]+10
            yanse = image.lab_to_rgb(yanse_lab)#lab转rgb
            while key.value() == 0:
                time.sleep_ms(1)
    lcd.display(img)
